<?php


namespace App\Service;


use App\Game\Core\Djs;
use App\Model\GameFreeOrderTask;
use App\Model\GameFreeTask;
use App\Model\GameFreeTaskLog;

class FreeOrderTaskService
{
    private static $game_id = 6;
    private static $taskTypeOne = 2;
    private static $taskTypeTwo = 3;

    public static function updateFreeOrderTask($task_type, $uid)
    {
        $game_id = self::$game_id;
        //先查找合法的免单任务记录
        $fotInfo = GameFreeOrderTask::getValidFreeOrderTask($uid, $game_id);
        if ($fotInfo['code']) {
            LogService::info('updateFreeOrderTask', $fotInfo);
            return $fotInfo;
        }
        //查找对应的加速任务
        $taskInfo = GameFreeTask::getValidFreeTask($task_type, $game_id);
        if ($taskInfo['code']) {
            LogService::info('updateFreeOrderTask', $taskInfo);
            return $taskInfo;
        }
        $where = [
            'uid' => $uid,
            'game_id' => $game_id,
            'task_id' => $taskInfo['data']['id'],
            'fot_id' => $fotInfo['data']['id'],
        ];

        $totalNum = GameFreeTaskLog::query()->where($where)->whereBetween('complete_time', [$fotInfo['data']['create_at'], $fotInfo['data']['end_at']])->count('id');
//        dd('totalNum', $totalNum);
        //是否超过总完成次数限制
        if ($totalNum >= $taskInfo['data']['total_limit']) {
            return ['code' => 0, 'msg' => '超过总完成次数限制！'];
        }
        $daliyNum = GameFreeTaskLog::query()->where($where)->where('complete_time', '>=', strtotime(date('Y-m-d')))->count('id');
//        dd('daliyNum', $daliyNum);
        //是否超过每日完成次数限制
        if ($daliyNum >= $taskInfo['data']['day_limit']) {
            return ['code' => 0, 'msg' => '超过每日完成次数限制！'];
        }
        //组合日志数据
        $time = time();
        $data = [
            'uid' => $uid,
            'game_id' => $game_id,
            'task_id' => $taskInfo['data']['id'],
            'fot_id' => $fotInfo['data']['id'],
            'prize_num' => $taskInfo['data']['prize_num'],
            'status' => 1,
            'is_get' => 2,
            'complete_time' => $time,
            'create_time' => $time
        ];
        //插入任务完成日志
        $res = GameFreeTaskLog::insertRecord($data);
        if ($res['code']) {
            LogService::error('GameFreeTaskLog:insertRecord', $res);
            return $res;
        }
        return ['code' => 0, 'msg' => '执行成功！'];
    }

    public static function updateMjFreeOrderTask($userArr)
    {
        foreach ($userArr as $v) {
            dd('updateMjFreeOrderTask daliy', $v['account']);
            self::updateFreeOrderTask(self::$taskTypeOne, $v['account']);
            if ($v['is_win'] == 1) {
                $playerInfo = Djs::getDjsPlayerData($v['account']);
                if ($playerInfo['stage'] >= 3) {
                    dd('updateMjFreeOrderTask djs', $v['account']);
                    self::updateFreeOrderTask(self::$taskTypeTwo, $v['account']);
                }
            }
        }
    }
}